﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.CourseManagement.DataAccess.DataEntity;

namespace Zhaoxi.CourseManagement.MysqlCommon
{
    public class MysqlConnect
    {
        private string UserName = "root";
        private string Password = "Aa@19950222";
        private string Host = "47.93.253.153";
        private uint PortName = 3306;
        private string DataBase = "bms";

        public UserEntity ToConnection(string userName, string pwd) 
        {
            try 
            {
                //与数据库连接的信息
                MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
                //
                builder.UserID = UserName;
                builder.Password = Password;
                builder.Server = Host;
                builder.Port = PortName;
                builder.Database = DataBase;

                MySqlConnection connection = new MySqlConnection(builder.ConnectionString);
                connection.Open();
                string sql = "select * from user where user_name=@user_name and password=@pwd";
                MySqlCommand command = new MySqlCommand(sql, connection);
                // 添加参数
                command.Parameters.Add(new MySqlParameter("@user_name", MySqlDbType.VarChar) { Value = userName });
                command.Parameters.Add(new MySqlParameter("@pwd", MySqlDbType.VarChar) { Value = pwd });

                MySqlDataReader reader = command.ExecuteReader();

                int count = reader.FieldCount;
                if (count == 0)
                {
                    return null;
                }
                while (reader.Read())
                {
/*                    int status = reader.GetInt16(4);
                    if (status == 2)
                    {
                        throw new Exception("当前用户没有权限使用此平台！");
                    }*/
                    UserEntity userInfo = new UserEntity();
                    userInfo.UserName = reader.GetString(1);
                    userInfo.RealName = reader.GetString(2);
                    userInfo.Password = reader.GetString(3);
                    userInfo.Avatar = reader.GetString(4);
                    return userInfo;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                
            }

            return null;
        }
    }
}
